/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

import fse from 'fs-extra';
import path from 'path';

import { BuildArtifactConst, BuildDirConst } from '../const/build-directory-const.js';
import { ProjectModelImpl } from '../model/project/project-model-impl.js';

import { AbstractProcessResourceIncrement } from './abstract/abstract-process-resource-increment.js';
import { TaskNames } from './common/task-names.js';
import { TargetTaskService } from './service/target-task-service.js';
import Task = TaskNames.Task;

/**
 * Stage 模型用于处理和生成Restool增量方式的编译、链接命令参数
 *
 * @since 2022/09/22
 */
export class ProcessResourceIncrement extends AbstractProcessResourceIncrement {
  protected FIRST_SUPPORT_RESTOOL_IDSMAP_APIVERSION = 10;
  protected idsMapDir: string;

  constructor(taskService: TargetTaskService) {
    super(taskService, Task.PREVIEW_PROCESS_RESOURCE);
    this.restCommandContent = this.pathInfo.getIntermediatesRes();
    this.outputDir = this.pathInfo.getIntermediatesRes();
    this.idsMapDir = path.resolve(this.outputDir!, BuildDirConst.IDS_MAP);
  }

  initCommandBuilder() {
    this.restoolCommandBuilder = this.getRestoolCommandBuilder();

    if (this.service.getModuleModel().isHapModule() || this.service.getModuleModel().isHspModule()) {
      this.restoolCommandBuilder.addAppScopeResourcesDir((this.projectModel as ProjectModelImpl).getAppRes().getResourcePath()); // App级别的资源
    }

    const bundleName: string = (this.projectModel as ProjectModelImpl).getAppRes().getAppResOpt().app.bundleName;
    this.restoolCommandBuilder
      .addJsonFile(this.processedJson!)
      .addModulePackName(bundleName)
      .addOutputDir(this.outputDir!)
      .addResTable(path.resolve(this.pathInfo.getGenerateSourceR(), BuildArtifactConst.RESOURCE_TABLE_H))
      .incrementalCompile();

    if (this.compileApiVersion >= this.FIRST_SUPPORT_RESTOOL_IDSMAP_APIVERSION) {
      this.restoolCommandBuilder.addIdsPath(this.idsMapDir);

      // 在存在id_defined.json文件的情况下，给restool传相应参数固定资源id
      if (fse.existsSync(path.resolve(this.idsMapDir, 'id_defined.json'))) {
        this.restoolCommandBuilder.addDefinedIds(this.idsMapDir);
      }
    }

    // HOS工程会单独传递HOS toolchain路径给restool
    if (!this.sdkInfo.isOhos) {
      this.restoolConfigBuilder.addDefinedSysIds(this.sdkInfo.getHosToolchainsDir());
    }
  }
}
